﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iLangl.Utils;
using System.Data;

namespace iLangl.BusinessModel.DAL.XMLStorage
{
	public class XmlStorageManager : BaseMockupStorageManager
	{

		private XmlStorageManager(string filename)
			: base(filename)
		{
		}

		~XmlStorageManager()
		{
			Save();
		}

		private static XmlStorageManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the XmlStorageManager.
		/// </summary>
		public static XmlStorageManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new XmlStorageManager(XMLStorageConfiguration.Instance.FilePathToStorage);
						}
					}
				}
				return instance;
			}
		}

		private dtoXmlStorage _storage = null;
		private object _lock = new object();
		
		public dtoXmlStorage Storage
		{
			get
			{
				lock (_lock)
				{
					if (_storage == null)
					{
						_storage = new dtoXmlStorage();

						if (!File.Exists(StorageFileName))
						{

							Save();
						}

						read();
					}

					return _storage;
				}
			}
		}

		protected override void readStorage()
		{
			_storage = new dtoXmlStorage();

			foreach (DataTable dataTable in _storage.Tables)
				dataTable.BeginLoadData();

			_storage.ReadXml(StorageFileName);

			foreach (DataTable dataTable in _storage.Tables)
				dataTable.EndLoadData();
		}
		protected override void saveStorage()
		{
			Storage.WriteXml(StorageFileName);
		}
		
		public void AcceptChanges()
		{
			Storage.AcceptChanges();
			Save();
		}
	}
}
